import axios from 'axios'
import { commonParams, options } from './config'
import jsonp from 'common/js/jsonp'

/**
 * 获取歌曲播放地址url
 * @param songmid
 * @return {Promise<string>}
 */
export async function getSongUrl (songmid) {
  const url = 'https://u.y.qq.com/cgi-bin/musicu.fcg'
  let opt = Object.assign({}, options, {
    name: 'getplaysongvkey9211579249510062'
  })
  const data = Object.assign({}, commonParams, {
    callback: 'getplaysongvkey9211579249510062',
    g_tk: '549603377',
    jsonpCallback: 'getplaysongvkey9211579249510062',
    loginUi: '646654379',
    hostUin: '0',
    format: 'jsonp',
    inCharset: 'utf8',
    outCharset: 'utf-8',
    notice: '0',
    platform: 'yqq',
    needNewCode: '0',
    data: JSON.stringify({
      req: {
        module: 'CDN.SrfCdnDispatchServer',
        method: 'GetCdnDispatch',
        param: { guid: '6005580000', calltype: 0, userip: '' }
      },
      req_0: {
        module: 'vkey.GetVkeyServer',
        method: 'CgiGetVkey',
        param: {
          guid: '6005580000',
          songmid: [songmid],
          songtype: [0],
          uin: '646654379',
          loginflag: 1,
          platform: '20'
        }
      },
      comm: { uin: 646654379, format: 'json', ct: 24, cv: 0 }
    })
  })
  try {
    let resp = await jsonp(url, data, opt)
    if (resp.req_0.data.midurlinfo[0].purl) {
      const baseUrl = 'http://111.202.98.145/amobile.music.tc.qq.com/'
      return baseUrl + resp.req_0.data.midurlinfo[0].purl
    }
  } catch (e) {
    console.log(e.message)
  }
  return ''
}

/**
 * 获取歌曲的歌词
 * @param songmid
 * @return {Promise<T>}
 */
export function getSongLyric (songmid) {
  const url = '/api/_getLyric'
  const params = Object.assign({}, commonParams, {
    '-': 'MusicJsonCallback_lrc',
    pcachetime: new Date(),
    songmid: songmid,
    g_tk: 2133783466,
    loginUin: 0,
    hostUin: 0,
    format: 'json',
    notice: 0,
    platform: 'yqq.json',
    needNewCode: 0
  })
  return axios
    .get(url, {
      params: params
    })
    .then(resp => {
      return Promise.resolve(resp.data)
    })
}

/**
 * 获取歌单数据
 * @param disstid
 * @return {Promise<T>}
 */
export function getDisc (disstid) {
  const url = '/api/getDisc'
  const params = Object.assign({}, commonParams, {
    type: 1,
    json: 1,
    utf8: 1,
    onlysong: 0,
    new_format: 1,
    disstid,
    g_tk: 709943229,
    loginUin: 0,
    hostUin: 0,
    notice: 0,
    platform: 'yqq.json',
    needNewCode: 0
  })
  return axios.get(url, {
    params: params
  }).then(resp => {
    return Promise.resolve(resp.data)
  })
}
